package com.wh.wisdomsite.xbox.server.controller.us;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.ba.entity.CommonFile;
import com.wh.wisdomsite.xbox.ba.service.ICommonFileService;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.us.CompanyIn;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.session.ServerSessionUser;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.us.entity.Company;
import com.wh.wisdomsite.xbox.us.service.ICompanyService;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.convert.ConvertTool;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static jdk.nashorn.internal.runtime.GlobalFunctions.decodeURI;

/**
 * 公司controller
 * @author 刘旭
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.server.controller.us
 * @date 2018年08月06日 22:37
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Controller
@RequestMapping(value = "/company")
public class CompanyController {
    private static final Log logger = LogFactory.getLog(CompanyController.class);

    @Autowired
    private ICompanyService iCompanyService;

    @Autowired
    private ICommonFileService iCommonFileService;

    /**
     * 跳转页面到公司方法
     * @return
     */
    @RequiresPermissions("rules:us_company_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index(){
        return "/us/company/companyList";
    }


    /**
     * 获取公司数据列表
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:us_company_find")
    @RequestMapping(value = "/companyList.do")
    public void companyList(HttpServletResponse response, CompanyIn in){
        try {
            logger.info("加载公司数据列表-->>开始");
            //设置分页
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            Page<Company> page = new Page<Company>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            EntityWrapper<Company> ewCompany = new EntityWrapper<Company>();
            ewCompany.setEntity(new Company());
            if(StringUtils.isNotEmpty(in.getName())){
                ewCompany.like("name",in.getName());
            }
            if(StringUtils.isNotEmpty(in.getRegisterID())){
                ewCompany.like("registerID",in.getRegisterID());
            }
            if(StringUtils.isNotEmpty(in.getCompanyType())){
                ewCompany.eq("compType",in.getCompanyType());
            }
            ewCompany.eq("dataState",1);
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewCompany = setEntityWrapper(ewCompany);
            }
            ewCompany.orderBy("compCode",true);
            Page<Company> companyPage = iCompanyService.selectPage(page,ewCompany);
            JSONObject json = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            if(companyPage.getRecords().size() > 0){
                List<Company> resultList = iCompanyService.getMenuListForSerch(companyPage.getRecords());
                for(Company company : resultList){
                    JSONObject object = new JSONObject(company);
                    object.put("registerDateFormat", DateTool.format(company.getRegisterDate(), "yyyy-MM-dd"));
                    jsonArray.put(object);
                }
            }
            json.put("total", companyPage.getTotal());
            json.put("rows", jsonArray);
            ResManager.getTextOut(response).print(json);
            logger.info("加载公司数据列表-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("加载公司数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 保存公司信息
     * @param company
     *  @param commonFile
     * @param response
     */
    @RequiresPermissions("rules:us_company_edit")
    @RequestMapping(value = "/companySave.do", method = RequestMethod.POST)
    public void companySave(Company company, CommonFile commonFile, String fileName, HttpServletResponse response){
        try{
            logger.info("保存公司信息-->>开始");
            Integer companyId = company.getCompanyId();
            String compCode = "";
            String compLogo = "";
            if(null == companyId){
                company.setCreateBy(UserUtils.getCurrentUser().getUsId());
            }else{
                Company companyOld = iCompanyService.selectById(companyId);
                compCode = companyOld.getCompCode();
                compLogo = companyOld.getCompLogo();
                company.setUpdateBy(UserUtils.getCurrentUser().getUsId());
            }
            //上传文件不为空
            if(StringUtils.isNotEmpty(commonFile.getFileId())){
                company.setCompLogo(commonFile.getFileId());
            }
            iCompanyService.saveCompany(company,compCode);
            //保存公司logo至附件表
            if(StringUtils.isNotEmpty(company.getCompLogo())
                    && StringUtils.isNotEmpty(commonFile.getFileId())
                    && !compLogo.equals(commonFile.getFileId())){
                commonFile.setName(fileName);
                commonFile.setCreateby(UserUtils.getCurrentUser().getUsId());
                commonFile.setFkId(String.valueOf(company.getCompanyId()));
                commonFile.setCreatedate(new Date());
                commonFile.setCompCode(UserUtils.getServerSessionUser().getFinalCompCode());
                iCommonFileService.insert(commonFile);
            }
            response.getWriter().write(JsonUtil_Org.returnTrue("保存公司信息成功"));
            logger.info("保存公司信息-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("保存公司信息-->>Exception" + e.getMessage());
        }
    }


    /**
     * 跳转至添加/修改页面
     * @param compId
     * @param request
     * @return
     */
    @RequestMapping("/toCompany")
    public String toCompany(String compId,HttpServletRequest request){
        logger.info("公司跳转-->>开始");
        Company company = new Company();
        Map commonFileMap = new HashMap();
        try{
            CommonFile commonFile = new CommonFile();
            commonFileMap = ConvertTool.objectToMap(commonFile);
            if(StringUtils.isNotEmpty(compId)){
                company = iCompanyService.selectById(compId);
                String compLogo = company.getCompLogo();
                if(StringUtils.isNotEmpty(compLogo)){
                    CommonFile commonFile1 = iCommonFileService.selectById(compLogo);
                    if(null != commonFile1){
                        commonFileMap = ConvertTool.objectToMap(commonFile1);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        request.setAttribute("company",company);
        request.setAttribute("registerDate", DateTool.format(company.getRegisterDate(), "yyyy-MM-dd"));
        request.setAttribute("commonFile",commonFileMap);
        logger.info("公司跳转-->>结束");
        return "/us/company/companyOption";
    }

    /**
     * 公司详情
     * @param id
     * @param request
     * @return
     */
    @RequiresPermissions("rules:us_company_view")
    @RequestMapping("/companyDesc.do")
    public String companyDesc(String id, HttpServletRequest request) {
        logger.info("公司详情-->>开始");
        Map<String , Object> company = iCompanyService.getMapById(id);
        if(company.get("createBy") != null){
            company.put("createBy", UserMapManager.getUserLoginNameInMap(company.get("createBy").toString()));
        }
        if(company.get("updateBy") != null){
            company.put("updateBy", UserMapManager.getUserLoginNameInMap(company.get("updateBy").toString()));
        }
        request.setAttribute("company", company);
        logger.info("公司详情-->>结束");
        return "/us/company/companyDesc";
    }

    /**
     * 删除公司信息
     * @param id
     * @param response
     * @return
     */
    @RequiresPermissions("rules:us_company_del")
    @RequestMapping("/deleteCompany.do")
    public void deleteCompany(String id, HttpServletResponse response) {
        logger.info("删除公司-->>开始");
        if(StringUtils.isNotEmpty(id)){
            if("1" == id){
                ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("公司删除失败"));
            }else{
                EntityWrapper<Company> ewCompany = new EntityWrapper<Company>();
                ewCompany.eq("parentId",id);
                ewCompany.eq("dataState","1");
                List<Company> companyList = iCompanyService.selectList(ewCompany);
                // 不存在子公司，才执行删除
                if(companyList.size() == 0){
                    iCompanyService.deleteById(Integer.valueOf(id));
                    ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("公司删除成功"));
                }else{
                    ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("公司删除失败"));
                }
            }
        }else{
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("公司删除失败"));
        }
        logger.info("删除公司-->>结束");
    }

    /**
     * 获取公司树形结构
     * @param response
     */
    @RequestMapping("/getTreeCompany.do")
    public void getTreeCompany(HttpServletResponse response) {
        try{
            logger.info("获取公司树形结构-->>开始");
            EntityWrapper<Company> ewCompany = new EntityWrapper<Company>();
            ewCompany.setEntity(new Company());
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            boolean isAdmin = UserUtils.isSysAdmin();
            if(!isAdmin){
                ewCompany = setEntityWrapper(ewCompany);
            }
            ewCompany.eq("dataState","1");
            ewCompany.orderBy("compCode",true);
            // 获取所有公司数据
            List<Company> allCompanyList = iCompanyService.selectList(ewCompany);
            JSONArray jsonArray = iCompanyService.toTreeCompany(allCompanyList,isAdmin);
            ResManager.getTextOut(response).print(jsonArray);
            logger.info("获取公司树形结构-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("获取公司树形结构-->>Exception" + e.getMessage());
        }
    }

    /**
     * 子账号修改根节点公司时获取所属公司
     * @param response
     * @param parentId
     */
    @RequestMapping("/getParentComp.do")
    public void getParentComp(HttpServletResponse response,String parentId) {
        try{
            logger.info("获取所属公司-->>开始");
            Company company = new Company();
            if (StringUtils.isNotEmpty(parentId)) {
                company = iCompanyService.selectById(parentId);
            }
            JSONObject obj = new JSONObject(company);
            ResManager.getTextOut(response).print(obj);
            logger.info("获取所属公司-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("获取所属公司-->>Exception" + e.getMessage());
        }
    }

    /**
     * 跳转至公司信息页面
     * @param request
     * @return
     */
    @RequestMapping("/toCompanyInformation.do")
    public String toCompanyInformation(HttpServletRequest request){
        logger.info("公司跳转-->>开始");
        Integer compId = UserUtils.getCurrentUser().getCompanyId();
        Map<String,Object> company = null;
        Map<String, Object> parentCompany = null;
        if(null!=compId){
            company = iCompanyService.getMapById(compId);
        }
        if(null!= company){
            if (company.get("parentId") != "0" && company.get("parentId") != null) {
                parentCompany = iCompanyService.getMapById((Serializable) company.get("parentId"));
            }
        }
        request.setAttribute("company",company);
        request.setAttribute("parentCompany",parentCompany);
        logger.info("公司跳转-->>结束");
        return "/us/company/companyInformation";
    }

    /**
     * 根据权限设置查询范围
     * @param ew
     * @return
     */
    public EntityWrapper setEntityWrapper(EntityWrapper ew) {
        ServerSessionUser serverSessionUser = UserUtils.getServerSessionUser();
        String dataScope = serverSessionUser.getDataScope();
        //设置一个查询用的代码
        String codeForFind = null;
        switch (dataScope) {
            case "1":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.like("compCode", codeForFind);
                }
                break;
            case "2":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.eq("compCode", codeForFind);
                }
                break;
            case "3":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.eq("compCode", codeForFind);
                }
                break;
            case "4":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.eq("compCode", codeForFind);
                }
                break;
            case "5":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.eq("compCode", codeForFind);
                }
                break;
            default:break;
        }
        return ew;
    }


    /**
     * 验证公司名称是否已经存在
     * @param companyName
     * @param oldCompanyName
     * @return
     */
    @RequestMapping(value = "/companyNameIsExists.do", method = RequestMethod.POST)
    public void companyNameIsExists(HttpServletResponse response, String companyName, String oldCompanyName){
        try {
            String name = (String) decodeURI("UTF-8",companyName);
            String oldName = (String) decodeURI("UTF-8",oldCompanyName);
            Map<String, Object> map = new HashMap<>();
            map.put("result", iCompanyService.companyNameIsExists(name, oldName));
            JSONObject json = new JSONObject(map);
            ResManager.getTextOut(response).print(json);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
